package fi.foyt.cs.api.users;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.oauth.protectedresource.ScopedResource;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;

import fi.foyt.cs.Scope;
import fi.foyt.cs.api.APIResource;
import fi.foyt.cs.api.json.EntityRendererVault;
import fi.foyt.cs.controller.UserController;
import fi.foyt.cs.persistence.domainmodel.items.Inventory;
import fi.foyt.cs.persistence.domainmodel.items.InventoryItem;
import fi.foyt.cs.persistence.domainmodel.user.User;

public class GetInventoryResource extends APIResource implements ScopedResource {

  @Get("json")
  @Post("json")
  public JsonRepresentation represent() throws ResourceException {
    long startTime = System.currentTimeMillis();
    getLogger().info("API call /v1/users/getInventory");
    
    UserController userController = new UserController();
    
    JSONObject result = new JSONObject();
    try {
      User user = userController.findUserByIdentifier(getClientInfo().getUser().getIdentifier());
      if (user != null) {
        Inventory inventory = userController.findInventoryByUser(user);
        List<InventoryItem> inventoryItems = userController.listInventoryItems(inventory);
        
        JSONArray inventoryItemsJson = new JSONArray();
        
        for (InventoryItem inventoryItem : inventoryItems) {
          inventoryItemsJson.put(EntityRendererVault.getInstance().renderEntity(getLocale(), inventoryItem));
        }
        
        result.put("money", inventory.getMoney());
        result.put("inventoryItems", inventoryItemsJson);
      } else {
        throw new ResourceException(Status.CLIENT_ERROR_UNAUTHORIZED, "User not found");
      }
      
    } catch (JSONException e) {
      this.setStatus(Status.SERVER_ERROR_INTERNAL);
      return null;
    }
    
    getLogger().info("API call /v1/users/getInventory finished in " + (System.currentTimeMillis() - startTime) + "ms");

    return new JsonRepresentation(result);
  }

  public String getOwner(Reference uri) {
    return null;
  }

  public String[] getScope(Reference uri) {
    return new String[] { Scope.Inventory.getIntenal() };
  }
}
